package com.jiang.竞赛.周赛.四三二.Q3417;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/01/12 23:59
 */
class Solution {
    public List<Integer> zigzagTraversal(int[][] grid) {
        List<Integer> list = new ArrayList<>();
        int row = grid.length;
        int col = grid[0].length;

        // 每两行呈周期， 如果有偶数列，那么奇数行一定会经过最后一列元素，相反一定会经过倒数第二列
        int end = col % 2 == 0 ? col - 1 : col - 2;
        int i = 0;
        int j = 0;
        while (i < row) {

            j = 0;
            while (j < col) {
                list.add(grid[i][j]);
                j += 2;
            }

            if (i + 1 == row) break;

            j = end;
            while (j >= 0) {
                list.add(grid[i + 1][j]);
                j -= 2;
            }

            i += 2;
        }

        return list;
    }
}
